﻿using System;
using System.Collections.Generic;
using System.Text;

using YouHP.Model;
using YouHP.Utility;
using YouHP.Config;
using YouHP.BLL;


namespace YouHP.Pages.User
{
    // UGLY!!!!
    public class ValidationCode
    {
        public string url;
        public string answer;
        public ValidationCode(string _url, string _answer)
        {
            this.url = _url;
            this.answer = _answer;
        }
    }   // class ValidationCode

    public class ValidationCodeHelper
    {
        public static ValidationCode vc1 = new ValidationCode("/support/Alpha/validation/1001.jpg", "2");
        public static ValidationCode vc2 = new ValidationCode("/support/Alpha/validation/1002.jpg", "6");
        public static ValidationCode vc3 = new ValidationCode("/support/Alpha/validation/1003.jpg", "82");
        public static ValidationCode vc4 = new ValidationCode("/support/Alpha/validation/1004.jpg", "4");
        public static ValidationCode vc5 = new ValidationCode("/support/Alpha/validation/1005.jpg", "222");
        public static ValidationCode vc6 = new ValidationCode("/support/Alpha/validation/1006.jpg", "3");

        public static List<ValidationCode> getAllValidationCodes()
        {
            List<ValidationCode> list = new List<ValidationCode>();
            list.Add(vc1);
            list.Add(vc2);
            list.Add(vc3);
            list.Add(vc4);
            list.Add(vc5);
            list.Add(vc6);
            // Add other validation code here.
            return list;
        }

        public static ValidationCode getRandomValidationCode()
        {
            List<ValidationCode> all = getAllValidationCodes();
            int     size = all.Count;
            if (0 == size)
                return null;

            DateTime    datetime = DateTime.Now;
            int         second = datetime.Second;
            int randomeNum = second % size;
            return all[randomeNum];
        }

        public static bool validate(ValidationCode vc, string answer)
        {
            if (string.Equals(vc.answer, answer.Trim()))
                return true;
            return false;
        }

    }   // class ValidationCodeHelper

    public class Register : BasePage
    {
        protected DateTime birthday ; 
        protected string agree = "";
        PatientRecordInfo patientRecord;
        protected const int DeseaseOtherID = 10;
        protected UserInfo _User = new UserInfo();
        public List<DistrictInfo> mProvinceList = new List<DistrictInfo>();
        public List<DistrictInfo> mCityList = new List<DistrictInfo>();
        public Dictionary<int, string> diseaseDict = new Dictionary<int, string>();
        public static ValidationCode vc = new ValidationCode("", "");

        protected override void ShowPage()
        {
            base.ShowPage();
            this.SetTitle("用户注册");
            this.AddLocation("用户注册", "/support/Alpha/User/Register.aspx");
            //this.AddLinkCss("/support/Alpha/css/reg.css");
            this.AddScriptSrc("/support/Alpha/Js/mootools.js");

            HandleCommon();

            if (!IsPost)
            {
                vc = ValidationCodeHelper.getRandomValidationCode();
            }

            if (IsPost)
            {
                HandleRegister();
            }

        }

        protected void HandleCommon()
        {
            mProvinceList = DistrictBLL.Instance.GetDistrictListByParent(0);

        }

        private void HandleRegister()
        {
            string validitionCode = RequestTools.GetFormString("ValidationCode");
            if (validitionCode.Trim() == "" || validitionCode.Trim()!=vc.answer)
            {
                AddErrLine("请输入正确的验证码!");
                return;
            }

            agree = RequestTools.GetFormString("term");
            if (agree != "on")
            {
                AddErrLine("请先阅读网站协议");
                MsgboxShowbackLink = "true";
                return;
            }

            bool regsucc  = false;
            bool addDeseaseRecord = true;
            UserData.UserName = RequestTools.GetFormString("username");
           
            #region BasicIno

            UserData.Gender = "未知";
            UserData.Avatar = "/support/Alpha/avatars/male.gif";
            UserData.Email = RequestTools.GetFormString("email");
            UserData.Password = Utils.MD5(RequestTools.GetFormString("password"), 16);
            UserData.UserTypeId = 1;
            UserData.ProvinceId = RequestTools.GetFormInt("province", 0);
            string pwd = RequestTools.GetFormString("password");
            UserData.IsActive = 1;

            #endregion          
          

            if (UserData.UserTypeId == Constants.USER_PATIENT)
            {
                UserData.UserTypeName = "病人";
            }
            else if (UserData.UserTypeId == Constants.USER_DOCTOR)
            {
                UserData.UserTypeName = "医生";
            }
            patientRecord = ValidatePatientRecord();
            try
            {
                if (UserBLL.Instance.CheckExsitUserName(UserData.UserName))
                {
                    this.AddMsgLine("用户名：" + UserData.UserName + "在数据库中，已经存在！");
                    this.AddMsgLine("请再次尝试其他的用户名，谢谢");
                    regsucc = false;
                }
                else
                {
                    if (UserBLL.Instance.CreateNewUser(UserData, pwd) && patientRecord.DiseaseId != 0)
                    {
                        UserInfo registeredUser = UserBLL.Instance.GetUserInfo(UserData.UserName);
                        patientRecord.PatientId = registeredUser.Id;
                        UserData = UserBLL.Instance.GetUserInfo(UserData.UserName);
                        if (patientRecord.DiseaseId != DeseaseOtherID)
                        {
                            addDeseaseRecord = PatientBLL.Instance.AddPatientRecord(patientRecord);
                        }
                        if (addDeseaseRecord)
                        {
                            this.AddMsgLine("恭喜您注册成功，您已成为优医网大家庭又一成员");
                            this.AddMsgLine("从现在开始，您可以使用优医网为您提供的专业服务。");
                            CookiesTools.WriteUserInfoCookie(UserData.UserName, UserData.Password, UserData.Id, 5256000);
                            SetUrl("/User/HomePage.aspx");
                            SetMetaRefresh();
                            regsucc = true;
                        }
                    }
                    else
                    {
                        /*处理失败*/
                    }
                }
            }
            catch(Exception e)
            {
                this.AddErrLine(e.ToString());
            }

            if (regsucc == false)
            {
                this.AddErrLine("注册失败");
            }
        }

        private PatientRecordInfo ValidatePatientRecord()
        {
            PatientRecordInfo patientRecordInfo = new PatientRecordInfo();
            int diseaseIdInt = RequestTools.GetFormInt("diseaseId",0);
            string diseaseIdString = diseaseIdInt.ToString();
            diseaseDict.Add(0, "-请选择-");
            diseaseDict.Add(1, "高血压病");
            diseaseDict.Add(2, "高血脂");
            diseaseDict.Add(3, "克罗恩病");
            diseaseDict.Add(4, "溃疡性结肠炎");
            diseaseDict.Add(5, "糖尿病");
            diseaseDict.Add(6, "特发性血小板减少性紫癜");
            diseaseDict.Add(7, "慢性粒细胞白血病");
            diseaseDict.Add(8, "慢性乙型肝炎/携带者");
            diseaseDict.Add(9, "多发性骨髓瘤");
            diseaseDict.Add(20, "支气管哮喘");
            diseaseDict.Add(10, "其他");

            string diseaseName = diseaseDict[diseaseIdInt];
            int diseaseId = 0;
            if (!string.IsNullOrEmpty(diseaseIdString))
            {
                try
                {
                    diseaseId = Convert.ToInt32(diseaseIdString);
                }
                catch (Exception e)
                { }
            }
            if (diseaseId != 0)
            {
                patientRecordInfo.DiseaseId = diseaseId;
                if (!string.IsNullOrEmpty(diseaseName))
                {
                    patientRecordInfo.DiseaseName = diseaseName;
                }
            }
            patientRecordInfo.StartDate = DateTime.Today.AddYears(-1);
            patientRecordInfo.ConfirmDate = DateTime.Today.AddYears(-1);
            patientRecordInfo.ConfirmHospital = "";
            return patientRecordInfo;
        }

    }
}
